import { calculateWordCount, createEmptyContent } from '../../../utils/documentUtils'
import { ContentType, type Content } from '../../../types/document'
import type { DocumentStats, DocumentViewState, DocumentTheme } from './types'

export const defaultTheme: DocumentTheme = 'light'

export const defaultStats: DocumentStats = {
  wordCount: 0,
  characterCount: 0
}

export const createInitialState = (): DocumentViewState => ({
  currentDocument: null,
  draftContent: '',
  isDirty: false,
  isLoading: false,
  lastSavedAt: null,
  error: null,
  theme: defaultTheme,
  stats: { ...defaultStats }
})

export const deriveStats = (content: string): DocumentStats => ({
  wordCount: calculateWordCount(content),
  characterCount: content.length
})

export const ensureTextDocument = (content?: Content | null): Content => {
  if (content && content.type === ContentType.TEXT_DOCUMENT) {
    return content
  }
  return createEmptyContent(ContentType.TEXT_DOCUMENT, '')
}

export const mergeDraftIntoContent = (content: Content, draft: string): Content => {
  if (content.type !== ContentType.TEXT_DOCUMENT) {
    return content
  }

  const now = new Date()

  return {
    ...content,
    updatedAt: now,
    data: {
      ...content.data,
      content: draft,
      wordCount: calculateWordCount(draft)
    }
  }
}
